<?php

namespace common\models;

use Yii;
use Resize\Gd2;
use Resize\Clear;

/**
 * This is the model class for table "product".
 *
 * @property integer $id_product
 * @property integer $id_company
 * @property integer $id_category_company
 * @property integer $id_category_online
 * @property integer $product_type
 * @property integer $product_parent
 * @property string $code
 * @property string $name
 * @property string $description
 * @property string $price
 * @property string $origin_price
 * @property string $image
 * @property integer $status
 * @property integer $total_quantity
 * @property string $updated
 * @property string $created
 *
 * @property Company $idCompany
 * @property ProductAttribute[] $productAttributes
 * @property ProductBranch[] $productBranches
 */
class Product extends \yii\db\ActiveRecord
{
    const TYPE_NORMAL = 1;
    const TYPE_GROUP = 2;
    const TYPE_COMBO= 3;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'product';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_company','id_category_company','product_type','total_quantity','name'],'required'],
            [['id_company', 'id_category_company', 'id_category_online', 'product_type', 'product_parent', 'status', 'total_quantity'], 'integer'],
            [['description'], 'string'],
            [['price', 'origin_price'], 'number'],
            [['updated', 'created','code'], 'safe'],
            [['name', 'image'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_product' => 'Id Product',
            'id_company' => 'Id Company',
            'id_category_company' => 'Id Category Company',
            'id_category_online' => 'Id Category Online',
            'product_type' => 'Product Type',
            'product_parent' => 'Product Parent',
            'name' => 'Name',
            'description' => 'Description',
            'price' => 'Price',
            'origin_price' => 'Origin Price',
            'image' => 'Image',
            'status' => 'Status',
            'total_quantity' => 'Total Quantity',
            'updated' => 'Updated',
            'created' => 'Created',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdCompany()
    {
        return $this->hasOne(Company::className(), ['id_company' => 'id_company']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductAttributes()
    {
        return $this->hasMany(ProductAttribute::className(), ['id_product' => 'id_product']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductBranches()
    {
        return $this->hasMany(ProductBranch::className(), ['id_product' => 'id_product']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'id_category_online']);
    }
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategoryCompany()
    {
        return $this->hasOne(CategoryCompany::className(), ['id_category_company' => 'id_category_company']);
    }
    
    /**
     * 
     * @param type $insert
     * @return boolean
     */
    public function beforeSave($insert) {
        parent::beforeSave($insert);
        if(!strlen($this->code)){
            $this->code = time();
        }
        return true;
    }
    
    /**
     * 
     * @return type
     */
    public static function getListType(){
        return [
            self::TYPE_NORMAL => 'Sản phẩm thông thường',
            self::TYPE_GROUP => 'Sản phẩm nhóm',
            self::TYPE_COMBO => 'Sản phẩm combo',
        ];
    }
    
    /**
     * 
     */
    public function getTextType(){
        $type = self::getListType();
        if(isset($type[$this->product_type])){
            return $type[$this->product_type];
        }
        return "";
    }

        /**
     * 
     */
    public function moveImage(){
        $file = \Yii::$app->params['PathImageProductTmp'].$this->image;
        if($this->image && file_exists($file)){
            if (!is_dir(\Yii::$app->params['PathImageProduct'] . $this->id_company)) {
                mkdir(\Yii::$app->params['PathImageProduct'] . $this->id_company, 0777);
            }
            $ext = pathinfo($file, PATHINFO_EXTENSION);
            $new_name = \Yii::$app->params['PathImageProduct'] . $this->id_company . DIRECTORY_SEPARATOR .$this->id_product.".".$ext; 
            rename($file, $new_name);
            $image = $this->id_product.".".$ext;
            $this->updateAttributes(['image' => $image]);
        }
    }
    
    /**
     * 
     */
    public function getUrlImage($width = 200, $heigth = 200) {
        $baseUrl = Yii::$app->urlManagerFrontEnd->baseUrl;
        $real = \Yii::$app->params['PathImageProduct'] . $this->id_company . DIRECTORY_SEPARATOR . $this->image;
        if (file_exists($real) && $this->image) {
            $newFile = $width."_".$heigth."_".$this->image;
            $fileResize = \Yii::$app->params['PathImageCache'] . $this->id_product . DIRECTORY_SEPARATOR . $newFile;
            if (!is_dir(\Yii::$app->params['PathImageCache'] . $this->id_product)) {
                mkdir(\Yii::$app->params['PathImageCache'] . $this->id_product, 0777);
            }
            if (!file_exists($fileResize)) {
                $obImage = new Gd2();
                $obImage->open($real);
                $obImage->keepAspectRatio(true);
                $obImage->keepFrame(true);
                $obImage->keepTransparency(true);
                $obImage->constrainOnly(false);
                $obImage->backgroundColor(array(255, 255, 255));
                $obImage->quality(90);
                $obImage->resize($width, $heigth);
                $obImage->save($fileResize);
            }
            return Yii::$app->params['UrlRoot'].$baseUrl . "/files/cache/" . $this->id_product . "/" . $newFile;
        }
        return Yii::$app->params['UrlRoot'].$baseUrl . "/files/product/default.jpg";
    }
}
